﻿using System;
using System.Collections.Generic;

using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using WLMCoreLibrary;
using MiWebSite_Core;

namespace MWS_AddDirectory.MisAnuncios.Perfil
{
    public partial class password : System.Web.UI.Page
    {
        public dbConnector ConexionDB;
        public WebSiteMainConfiguration config;
        protected void Page_Load(object sender, EventArgs e)
        {
            config = WebSiteMainConfiguration.GetConfig();
            if (Request.QueryString["edit"] != null)
                guardarDatosUsuario();
        }

        protected void guardarDatosUsuario()
        {
            if (CurrentClient.Id != 0)
            {
                ConexionDB = new dbConnector(config.Connections["WebSite"].value);
                Response.ContentType = "text/xml";
                try
                {
                    Cliente cliente = new Cliente(CurrentClient.Id, ref ConexionDB);
                    if (cliente.id != 0)
                    {
                        SaltedHash hash = new SaltedHash();
                        string passCripted = hash.GetStringHash(txtCurrentPassword.Text, cliente.salt);
                        if (passCripted == cliente.password)
                        {
                            if (txtNewPassword.Text == txtConfirmPassword.Text)
                            {

                                string data = txtNewPassword.Text;
                                string newHash = hash.GetStringHash(data, cliente.salt);

                                cliente.password = newHash;
                                cliente.Save();
                                txtNewPassword.Text = "";
                                txtCurrentPassword.Text = "";
                                txtConfirmPassword.Text = "";
                                cliente.DatoTemporal = data;
                                cliente.EnviarEmailRecuperacionPassword(data);
                                SuccessObject success = new SuccessObject();
                                success.Code = SuccessCode.RegistryUpdated;                
                                Response.Write(WLMFunctions.SerializeObject(success, true));
                            }

                        }
                        ErrorObject error = new ErrorObject(ErrorCode.UserWrongPassword, "","", "");                       
                        Response.Write(WLMFunctions.SerializeObject(error, true));

                    }
                }
                catch (Exception ex)
                {
                    ErrorObject error = new ErrorObject(ErrorCode.UserDontExist, ex.Message, ex.Message, ex.StackTrace);
                    Response.Write(WLMFunctions.SerializeObject(error, true));

                }
                ConexionDB.CloseConnection();
                Response.End();
            }
        }
    }
}